﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib; 

namespace mojoPortal.Web.RS.SBM.NewsLetter
{
    public partial class RSManageNewsLetter : RSBasePage
    {

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }


        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                InitializeReadyServicePage("Manage News Letter");
                RSUserIdentity userIdentity = GetRSUserIdentity();
                RSSBMDataLookupLoader.LoadNewsLetterTemplateDDL(userIdentity.RSCompanyId, ddlTemplates);
                RSSBMDataLookupLoader.LoadNewsLetterDDL(userIdentity.RSCompanyId, ddlNewsLetters);
            }
        }

        protected void ddlTemplate_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            ddlNewsLetters.SelectedValue = "0";
            int newsletterid = Convert.ToInt32(ddlTemplates.SelectedValue.ToString());
            hfNewsLetterId.Value = newsletterid.ToString();
            hfIsTemplate.Value = "1";
            txtNewsLetterTitle.Text = "";
            RSUserIdentity userIdentity = GetRSUserIdentity();
            RadEditor1.Content = LoadNewsLetterData(userIdentity.RSCompanyId, newsletterid);
            btnPreview.Attributes.Add("OnClick", "javascript:return fnLaunchWin('/RS/SBM/NewsLetter/PreviewNewsLetter.aspx?newsletterid=" + newsletterid.ToString() + "','NewsLetter',600,600);");
            btnSave.Text = "Save As";
            if (newsletterid > 0)
            {
                btnSave.Visible = true;
                btnPreview.Visible = true;
                btnSendNewLetter.Visible = false;
            }
        }

        protected void ddlNewsLetter_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            ddlTemplates.SelectedValue = "0";
            int newsletterid = Convert.ToInt32(ddlNewsLetters.SelectedValue.ToString());
            hfNewsLetterId.Value = newsletterid.ToString();
            hfIsTemplate.Value = "0";
            txtNewsLetterTitle.Text = ddlNewsLetters.SelectedItem.Text;
            RSUserIdentity userIdentity = GetRSUserIdentity();
            RadEditor1.Content = LoadNewsLetterData(userIdentity.RSCompanyId, newsletterid);
            btnPreview.Attributes.Add("OnClick", "javascript:return fnLaunchWin('/RS/SBM/NewsLetter/PreviewNewsLetter.aspx?newsletterid=" + newsletterid.ToString() + "','NewsLetter',600,600);");
            btnSave.Text = "Save";
            if (newsletterid > 0)
            {
                btnSave.Visible = true;
                btnPreview.Visible = true;
                btnSendNewLetter.Visible = true;
            }
        }

        public string LoadNewsLetterData(int companyid, int newsletterid)
        {
            string data = "";
            if (companyid > 0 && newsletterid > 0)
            {
                String strSQL = "select * from rs_tblNewsLetter where newsletterid=@newsletterid and companyid=@companyid";
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@companyid";
                param.Value = companyid;
                myCommand.Parameters.Add(param);

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@newsletterid";
                param.Value = newsletterid;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                if (myDataReader.HasRows)
                {
                    myDataReader.Read();
                    data = myDataReader["Description"].ToString();
                }

                myConnection.Close();
            }
            return data;
        }

        protected void btnSave_Click(Object sender, EventArgs e)
        {
            int newsletterid = hfNewsLetterId.Value == "" ? 0 : int.Parse(hfNewsLetterId.Value);
            if (hfIsTemplate.Value == "1")
                SaveNewsLetterByID(0);
            else
                SaveNewsLetterByID(newsletterid);
        }

        protected void btnSendNewLetter_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (SendNewsLetterToCompanyContacts(userIdentity.RSCompanyId, userIdentity.RSCompanyName, userIdentity.RSCompanyEmail, RadEditor1.Content))
                ucModalActionMessageControl.ShowModal("Thank you.  Your email message has been sent.", "", true);
        }

        private bool SendNewsLetterToCompanyContacts(int companyid, string companyname, string companyemail, string emailcontent)
        {
            bool ret = false;
            String strSQL = "select email from rs_tblContact where companyid=@companyid and email is not null";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (myDataReader.HasRows)
            {
                string subject = companyname + " - News Letter";
                string SMTPServer = ConfigurationManager.AppSettings["SMTPServer"].ToString();
                string SMTPUser = ConfigurationManager.AppSettings["SMTPUser"].ToString();
                string SMTPPassword = ConfigurationManager.AppSettings["SMTPPassword"].ToString();
                System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
                eMail.IsBodyHtml = true;
                eMail.Body = emailcontent;
                eMail.From = new System.Net.Mail.MailAddress(companyemail);
                while (myDataReader.Read())
                {
                    if (myDataReader["Email"].ToString().Length > 0)
                        eMail.To.Add(new System.Net.Mail.MailAddress(myDataReader["Email"].ToString()));
                }
                eMail.Subject = subject;
                System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();

                SMTP.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPassword);
                SMTP.Host = SMTPServer;
                SMTP.Send(eMail);
                eMail.Dispose();
                ret = true;
            }
            myConnection.Close();
            return ret;
        }

        
        private void SaveNewsLetterByID(int newsletterid)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                string description = RadEditor1.Content;
                string title = txtNewsLetterTitle.Text;

                SqlCommand sqlCmd = new SqlCommand();
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, userIdentity.RSCompanyId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@NewsLetterID", SqlDbType.Int, 0, ParameterDirection.Input, newsletterid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Title", SqlDbType.NVarChar, 25, ParameterDirection.Input, title);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Description", SqlDbType.NVarChar, -1, ParameterDirection.Input, description);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);

                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveNewsLetter");
                SQLHelper.ExecuteScalarCmd(sqlCmd);
                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                ucModalActionMessageControl.ShowModal("News Letter Successfully Saved!", "", true);
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);

        }
    }
}


